package com.mogujie.tt.ui.activity;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iiordanov.bVNC.ConnectionBean;
import com.iiordanov.bVNC.Constants;
import com.iiordanov.bVNC.RemoteCanvasActivity;
import com.iiordanov.bVNC.Utils;
import com.mogujie.tt.R;
import com.mogujie.tt.config.PersonalUserInfoConstant;
import com.mogujie.tt.ui.base.QZBaseActivity;
import com.mogujie.tt.utils.Base64;
import com.mogujie.tt.utils.HttpUtilsApache;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2015/11/14.
 */
public class CloudComputerActivity extends QZBaseActivity {

    private static Map<String, Map<String, Object>> cpMap = new HashMap<String, Map<String, Object>>();
    private List<Map<String, Object>> mData;
    private static boolean isSXCP = false;
    public static int countR = 0;
    private String vmuidup;
    private String dyncpoolidup;

    private GridView gv_menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater.from(CloudComputerActivity.this).inflate(R.layout.tt_activity_cloud_computer, topContentView);
        showTopInformation("云电脑");
        obtainVirtualMachineList();
        initView();

    }

    private void obtainVirtualMachineList() {
        try {

            if ( PersonalUserInfoConstant.userid!=null&&!"".equals(PersonalUserInfoConstant.userid)) {

                // 异步请求获取虚拟机列表
                new getvmsList().executeOnExecutor(Executors.newCachedThreadPool());

            } else if(PersonalUserInfoConstant.userid ==null ||"".equals(PersonalUserInfoConstant.userid)) {
                Toast.makeText(CloudComputerActivity.this,"获取云电脑列表失败！",Toast.LENGTH_SHORT).show();
                CloudComputerActivity.this.finish();
            }
        }catch (Exception e){

        }

    }

    private void initView() {
        gv_menu = (GridView) this.findViewById(R.id.gv_menu);
    }

    private void initData() {
        List<MenuItem> menus = new ArrayList<MenuItem>();
      for(int i =0;i< mData.size();i++){
          String str = (String)mData.get(i).get("ItemText");
          menus.add(new MenuItem(R.drawable.win7, str, ""));
      }
      //  menus.add(new MenuItem(R.drawable.winxp, "Windows Xp", ""));

        // 计算margin
        int margin = (int) (getResources().getDisplayMetrics().density * 14 * 13 / 9);
        MenuItemAdapter adapter = new MenuItemAdapter(CloudComputerActivity.this, menus, margin);
        gv_menu.setOnItemClickListener(adapter);
        gv_menu.setOnItemLongClickListener(adapter);
        gv_menu.setAdapter(adapter);
    }

    private class MenuItem {
        public int menuIconRes;
        public String menuTitle;
        public String menuMsg;

        public MenuItem(int menuIconRes, String menuTitle, String menuMsg) {
            this.menuIconRes = menuIconRes;
            this.menuTitle = menuTitle;
            this.menuMsg = menuMsg;

        }
    }


    private class MenuItemAdapter extends BaseAdapter implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

        private List<MenuItem> menus;
        private LayoutInflater inflater;
        private int margin;
        private Context context;

        public MenuItemAdapter(Context context, List<MenuItem> menus, int margin) {
            inflater = LayoutInflater.from(context);
            this.menus = menus;
            this.margin = margin;
            this.context = context;
        }


        @Override
        public int getCount() {
            return menus.size();
        }

        @Override
        public Object getItem(int position) {
            return menus.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int height = parent.getHeight() / 3 - margin;
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.menu_item, parent, false);
                holder = new ViewHolder();
                holder.iv_menuIcon = (ImageView) convertView.findViewById(R.id.iv_menu_icon);
                holder.tv_menuTitle = (TextView) convertView.findViewById(R.id.tv_menu_title);
                holder.tv_menuMsg = (TextView) convertView.findViewById(R.id.tv_menu_msg);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            MenuItem item = menus.get(position);
            holder.iv_menuIcon.setImageResource(item.menuIconRes);
            holder.tv_menuTitle.setText(item.menuTitle);
            if (item.menuMsg.length() == 0) {
                holder.tv_menuMsg.setVisibility(View.GONE);
            } else {
                holder.tv_menuMsg.setVisibility(View.VISIBLE);
                holder.tv_menuMsg.setText(item.menuMsg);
            }
            convertView.setLayoutParams(param);
            return convertView;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            loginVirtualMachine(position);
            //Toast.makeText(context, "请稍后,正在进入 "+menus.get(position).menuTitle.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            String str = menus.get(i).menuTitle.toString();
            vmuidup =(String)mData.get(i).get("vmuid");
            dyncpoolidup =(String)mData.get(i).get("dyncpoolid");
            showShutdownRestartDialog(str);
            return true;
        }

        private class ViewHolder {
            ImageView iv_menuIcon;
            TextView tv_menuTitle;
            TextView tv_menuMsg;
        }

    }

    /**
     * 显示关机或者重启电脑
     */
    private void showShutdownRestartDialog(final String str) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.tt_dialog_computer_shutdown_restart);

        TextView tv_shutdown = (TextView) window.findViewById(R.id.tv_shutdown);
        tv_shutdown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(CloudComputerActivity.this, str + " 正在关机,请稍后......", Toast.LENGTH_SHORT).show();
                dlg.dismiss();

                String[] param = { vmuidup, dyncpoolidup };
                new CloseVM().executeOnExecutor(
                        Executors.newCachedThreadPool(), param);

            }
        });
        TextView tv_restart = (TextView) window.findViewById(R.id.tv_restart);
        tv_restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(CloudComputerActivity.this, str + " 正在重启,请稍后......", Toast.LENGTH_SHORT).show();
                dlg.dismiss();
                String[] param = {vmuidup, dyncpoolidup };
                new RebootVM().executeOnExecutor(
                        Executors.newCachedThreadPool(), param);

            }
        });

    }

    /**
     * 显示顶部信息
     */
    private void showTopInformation(String test) {
        if (test == null) {
            return;
        }
        setTopBarDisplay();

        setCenterText(test);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
     //   onDest();
    }

    public void onClickExit(View view) {
        finish();
    }



    /**
     * 获取虚拟机列表
     *
     * @author ch
     */
    public class getvmsList extends AsyncTask<String, Void, Void> {
        String getjsonstr = "";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... parm) {

            // 异步请求
            HttpUtilsApache httpGetorPostUtil = new HttpUtilsApache();

            Map<String, Object> params = new HashMap<String, Object>();
            // base64加密访问
            params.put("act", Base64.encode("getUserVmList".getBytes()));
            params.put("username", Base64.encode(PersonalUserInfoConstant.username.getBytes()));
            params.put("password", Base64.encode(PersonalUserInfoConstant.password.getBytes()));
            params.put("userid", Base64.encode(PersonalUserInfoConstant.userid.getBytes()));
            params.put("callback", "?");

            // params.put("username", ServiceManager.username);
            // params.put("password", ServiceManager.password);
            // params.put("userid", ServiceManager.userid);
            // params.put("callback", "?");

            String ip = "172.16.0.2:80";
            // base64加密访问
            String url = "http://" + ip + "/dashboard/site/act";

            // String url = "http://" + ip + "/dashboard/site/getUserVmList/";

            String strjson = "";

            try {
                strjson = httpGetorPostUtil.usHttpGet(url, params);

                if (strjson != null) {
                    int rtjson = strjson.indexOf("?(");
                    if (rtjson == 0) {
                        getjsonstr = strjson.substring(3, strjson.length() - 2);
                    }
                }
            } catch (Exception e) {
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            try {

                if (getjsonstr != null && !"".equals(getjsonstr)) {
                    cpMap.clear();
                    cpMap = new HashMap<String, Map<String, Object>>();
                    try {
                        JSONObject dataJson = new JSONObject(getjsonstr);
                        JSONArray arrayJson = dataJson.getJSONArray("vms");// 静态虚拟机
                        JSONArray arraypoolsJson = dataJson
                                .getJSONArray("vmpools");// 动态虚拟机

                        if (dataJson.getString("servertype").equals("SXCP")) {// 专业版
                            isSXCP = true;
                            mData = getDataSXCP(arrayJson);
                            initData();
                            Toast.makeText(CloudComputerActivity.this, "获取虚拟机列表！", Toast.LENGTH_SHORT).show();
                        }else{// 企业版
                            isSXCP = false;
                            mData = getDataNoSXCP(arrayJson, arraypoolsJson);
                            Log.v("CloudComputerActivity","mData = "+mData.toString());
                            initData();
                            Toast.makeText(CloudComputerActivity.this, "获取虚拟机列表！", Toast.LENGTH_SHORT).show();

                        }

                    } catch (JSONException e) {
                    }

                }
            } catch (Exception e) {
            }

        }

    }


    // 企业版虚拟机列表信息
    private List<Map<String, Object>> getDataNoSXCP(JSONArray arrayJson,
                                                    JSONArray arraypoolsJson) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        cpMap.clear();
        cpMap = new HashMap<String, Map<String, Object>>();

        try {
            // 遍历静态虚拟机
            if (arrayJson.length() > 0) {

                for (int i = 0; i < arrayJson.length(); i++) {
                    if (!arrayJson.isNull(i)) {

                        JSONObject jo = (JSONObject) arrayJson.get(i);

                        HashMap<String, Object> map = new HashMap<String, Object>();


                        // map.put("ItemImage", R.drawable.pl_zm02);// 添加图像资源的ID
                        map.put("ItemText", jo.get("vmname"));// 按序号做ItemText
                        map.put("vmuid", jo.get("vmuid"));
                        map.put("dyncpoolid", "");
                        // map.put("msg", "剩余13天");
                        list.add(map);
                    }

                }
            }

            // 遍历动态虚拟机
            if (arraypoolsJson.length() > 0) {

                for (int i = 0; i < arraypoolsJson.length(); i++) {
                    if (!arraypoolsJson.isNull(i)) {

                        JSONObject jo = (JSONObject) arraypoolsJson.get(i);

                        HashMap<String, Object> map = new HashMap<String, Object>();

                        // map.put("ItemImage", R.drawable.pl_zm02);// 添加图像资源的ID
                        map.put("ItemText", jo.get("dyncpoolname"));// 按序号做ItemText
                        map.put("vmuid", "");
                        map.put("dyncpoolid", jo.get("dyncpoolid"));
                        // map.put("msg", "剩余13天");
                        list.add(map);
                    }

                }
            }
        } catch (Exception e) {
        }

        return list;
    }


    // 专业版虚拟机列表信息
    private List<Map<String, Object>> getDataSXCP(JSONArray arrayJson) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        cpMap.clear();
        cpMap = new HashMap<String, Map<String, Object>>();
        try {
            for (int i = 0; i < arrayJson.length(); i++) {
                if (!arrayJson.isNull(i)) {
                    JSONObject jo = (JSONObject) arrayJson.get(i);
                    HashMap<String, Object> map = new HashMap<String, Object>();


                    // map.put("ItemImage", R.drawable.pl_zm02);// 添加图像资源的ID

                    map.put("ItemText", jo.get("vmname"));// 按序号做ItemText
                    map.put("vmuid", jo.get("uid"));
                    map.put("dyncpoolid", "");
                    // map.put("msg", "剩余13天");

                    Map<String, Object> map2 = new HashMap<String, Object>();
                    map2.put("vmdn", jo.get("vmdn"));
                    map2.put("spiceurl", jo.get("spiceurl"));
                    map2.put("spicepassword", jo.get("spicepassword"));
                    map2.put("spiceport", jo.get("spiceport"));
                    cpMap.put(jo.get("uid").toString(), map2);

                    list.add(map);
                }

            }
        } catch (Exception e) {
        }

        return list;
    }
    public static String ss_vmuid = "";
    public static String ss_ip = "";
    public static String ss_dyncpoolid = "";
    // 登录虚拟机
    private void loginVirtualMachine( int i){

        String getvmidAndDyncpoolid = (String)mData.get(i).get("dyncpoolid");
        String vmuid = "";
        String dyncpoolid = "";
        if (!getvmidAndDyncpoolid .equals("")) {//动态虚拟机
            dyncpoolid = getvmidAndDyncpoolid;
        } else {//静态虚拟机
                vmuid =(String)mData.get(i).get("vmuid");
        }
        ss_vmuid = vmuid;
        String ip = "172.16.0.2:80";
        ss_ip = ip;
        System.gc();
        if (isSXCP) {// 专业版
            // 开启虚拟机
            String[] parm = new String[] { PersonalUserInfoConstant.username,
                    PersonalUserInfoConstant.password, vmuid, ip };
          /*  new startVmSXCP().executeOnExecutor(
                    Executors.newCachedThreadPool(),
                    parm);*/
        } else {
            // String dyncpoolid =
            // item.get("dyncpoolid").toString();
            ss_dyncpoolid = dyncpoolid;
            // 开启虚拟机
            String[] parm = new String[] { PersonalUserInfoConstant.username,
                    PersonalUserInfoConstant.password, vmuid, ip, dyncpoolid };
            new startVm().executeOnExecutor(
                    Executors.newCachedThreadPool(),
                    parm);
        }
    }

    /**
     * 开启企业版虚拟机
     *
     * @author ch
     *
     */
    public class startVm extends AsyncTask<String, Void, Void> {
        String getjsonstr = "";
        String vmuid = "";
        String dyncpoolid = "";
        Map<String, Object> obj = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(String... parm) {
            ss_vmuid = "";
            ss_ip = "";
            ss_dyncpoolid = "";
            vmuid = parm[2];
            dyncpoolid = parm[4];
            try {
                if (dyncpoolid.length() > 0) {
                    obj = (Map<String, Object>) PersonalUserInfoConstant.conMap
                            .get(PersonalUserInfoConstant.username + dyncpoolid);
                } else {
                    obj = (Map<String, Object>) PersonalUserInfoConstant.conMap
                            .get(vmuid);
                }
            } catch (Exception e) {

            }
            // 异步请求
            if (countR == 0 || obj == null) {
                getjsonstr = startVMask(parm);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // 得到请求开启虚拟机的json信息
            // System.out.print(getjsonstr);
          /*  boolean bn = ServiceManager.startMyStart;
            if (bn) {*/
                if (countR == 0 || obj == null) {
                    if (getjsonstr.length() == 3) {
                        String newMessageInfo = "";
                        if ("400".equals(getjsonstr)) {
                            newMessageInfo = HttpUtilsApache.HTTP_404;
                        } else if ("500".equals(getjsonstr)) {
                            newMessageInfo = HttpUtilsApache.HTTP_500;
                        } else if ("900".equals(getjsonstr)) {
                            newMessageInfo = HttpUtilsApache.HTTP_900;
                        } else if ("901".equals(getjsonstr)) {
                            newMessageInfo = "您当前网络较不稳定，请重试。";// HttpGetorPostUtil.HTTP_901;
                        } else if ("902".equals(getjsonstr)) {
                            newMessageInfo = "您当前网络较不稳定，请重试。";// HttpGetorPostUtil.HTTP_902;
                        } else if ("903".equals(getjsonstr)) {
                            newMessageInfo = HttpUtilsApache.HTTP_903;
                        }

                        if (!"".equals(newMessageInfo)) {
                            Toast.makeText(CloudComputerActivity.this, newMessageInfo, Toast.LENGTH_SHORT)
                                    .show();
                        }


                    } else {

                        try {
                            JSONObject dataJson = new JSONObject(getjsonstr);
                            String successflag = dataJson.getString(
                                    "successflag").toString();
                            // successflag 1:失败 0：成功
                            if ("0".equals(successflag)) {
                                countR++;
                             //   if (bn) {
                                    // 链接ip
                                    String spicehost = dataJson.getString(
                                            "spicehost").toString();
                                    // 端口号
                                    String spiceport = dataJson.getString(
                                            "spiceport").toString();
                                    // 密码
                                    String spicepassword = dataJson.getString(
                                            "spicepassword").toString();
                                    Map<String, String> map = new HashMap<String, String>();
                                    map.put("spicehost", spicehost);
                                    map.put("spiceport", spiceport);
                                    map.put("spicepassword", spicepassword);
                                    if (dyncpoolid.length() > 0) {
                                        PersonalUserInfoConstant.conMap.put(PersonalUserInfoConstant.username
                                                + dyncpoolid, map);
                                        PersonalUserInfoConstant.isconnectErrS = PersonalUserInfoConstant.username
                                                + dyncpoolid;
                                    } else {
                                        PersonalUserInfoConstant.conMap.put(vmuid, map);
                                        PersonalUserInfoConstant.isconnectErrS = vmuid;
                                    }

                                    ActivityManager.MemoryInfo info = Utils
                                            .getMemoryInfo(CloudComputerActivity.this);
                                    if (info.lowMemory)
                                        System.gc();
                                    try {
                                        PersonalUserInfoConstant.showContext = CloudComputerActivity.this;
                                        ConnectionBean selected = updateSelectedFromView(
                                                CloudComputerActivity.this,
                                                spicehost,
                                                Integer.parseInt(spiceport),
                                                spicepassword);
                                        Intent intent = new Intent(
                                                CloudComputerActivity.this,
                                                RemoteCanvasActivity.class);
                                        intent.putExtra(Constants.CONNECTION,
                                                selected.Gen_getValues());
                                       /* if (dyncpoolid.length() > 0) {
                                            intent.putExtra("fileName",
                                                    username + dyncpoolid);
                                            ServiceManager.myfileName = username
                                                    + dyncpoolid;
                                        } else {
                                            intent.putExtra("fileName",
                                                    username + vmuid);
                                            ServiceManager.myfileName = username
                                                    + vmuid;
                                        }*/

                                        startActivity(intent);
                                 //       CloudComputerActivity.this.finish();
                                    } catch (Exception e) {
                                        // System.out.println("-------------->error "+e.toString());
                                        // Toast.makeText(getActivity(),
                                        // e.toString(), 1).show();
                                    }
                             //   }
                            } else {
                                Toast.makeText(CloudComputerActivity.this,
                                        "开启系统失败，请重试...", Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            Toast.makeText(CloudComputerActivity.this, "开启系统出错，请联系管理员...",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                } else {
                    Map<String, Object> objMap = null;
                    try {
                        if (dyncpoolid.length() > 0) {
                            objMap = (Map<String, Object>) PersonalUserInfoConstant.conMap
                                    .get(PersonalUserInfoConstant.username + dyncpoolid);
                            PersonalUserInfoConstant.isconnectErrS = PersonalUserInfoConstant.username
                                    + dyncpoolid;
                        } else {
                            objMap = (Map<String, Object>) PersonalUserInfoConstant.conMap
                                    .get(vmuid);
                            PersonalUserInfoConstant.isconnectErrS = vmuid;
                        }
                    } catch (Exception e) {

                    }

                    if (objMap != null) {
                     //   if (bn) {
                            // 链接ip
                            String spicehost = objMap.get("spicehost")
                                    .toString();
                            // 端口号
                            String spiceport = objMap.get("spiceport")
                                    .toString();
                            // 密码
                            String spicepassword = objMap.get("spicepassword")
                                    .toString();

                            ActivityManager.MemoryInfo info = Utils
                                    .getMemoryInfo(CloudComputerActivity.this);
                            if (info.lowMemory)
                                System.gc();
                            try {
                                PersonalUserInfoConstant.showContext = CloudComputerActivity.this;
                                ConnectionBean selected =
                                        updateSelectedFromView(CloudComputerActivity.this,
                                                spicehost,
                                                Integer.parseInt(spiceport),
                                                spicepassword);
                                Intent intent = new Intent(CloudComputerActivity.this,
                                        RemoteCanvasActivity.class);
                                intent.putExtra(Constants.CONNECTION,
                                        selected.Gen_getValues());
                             /*   if (dyncpoolid.length() > 0) {
                                    intent.putExtra("fileName", username
                                            + dyncpoolid);
                                    ServiceManager.myfileName = username
                                            + dyncpoolid;
                                } else {
                                    intent.putExtra("fileName", username
                                            + vmuid);
                                    ServiceManager.myfileName = username
                                            + vmuid;
                                }*/

                                startActivity(intent);
                            //    CloudComputerActivity.this.finish();
                            } catch (Exception e) {
                            }

                     //   }
                    } else {

                        String[] parm = new String[] { PersonalUserInfoConstant.username, PersonalUserInfoConstant.password,
                                ss_vmuid, ss_ip, ss_dyncpoolid };
                        new startVm().executeOnExecutor(
                                Executors.newCachedThreadPool(), parm);
                    }
                }

           /* } else {
                dialog.dismiss();
            }*/

        }
    }

    /**
     * 请求开启虚拟机
     *
     * @return
     */
    private String startVMask(String[] parm) {
        String getjsonstr = "";
        HttpUtilsApache httpGetorPostUtil = new HttpUtilsApache();

        Map<String, Object> params = new HashMap<String, Object>();
        // base64加密访问
        params.put("act", Base64.encode("startvm".getBytes()));
        params.put("username", Base64.encode(parm[0].getBytes()));
        params.put("password", Base64.encode(parm[1].getBytes()));
        params.put("vmuid", Base64.encode(parm[2].getBytes()));
        params.put("ip", Base64.encode(parm[3].getBytes()));
        params.put("mac", "");//改为空
        params.put("dyncpoolid", Base64.encode(parm[4].getBytes()));
        params.put("callback", "?");
        params.put("time", System.currentTimeMillis());

        String ip = "172.16.0.2:80";
        // base64
        String url = "http://" + ip + "/dashboard/site/act";

        String strjson = "";

        strjson = httpGetorPostUtil.usHttpGet(url, params);
     //   System.out.println("-->请求虚拟机：" + strjson);
        if (strjson != null) {
            int rtjson = strjson.indexOf("?(\"");
            if (rtjson == 0) {
                getjsonstr = strjson.substring(3, strjson.lastIndexOf("\")"));
            } else {
                getjsonstr = strjson;
            }
        }

        return getjsonstr;
    }

    private static ConnectionBean updateSelectedFromView(Context context,
                                                         String ip, int port, String pwd) {
        ConnectionBean selected = new ConnectionBean(context);
        selected.setConnectionType(0);
        selected.setAddress(ip);
        selected.setPort(port);
        selected.setTlsPort(-1);
        selected.setSshPort(22);
        selected.setNickname("");
        selected.setSshServer("");
        selected.setSshUser("");
        selected.setKeepSshPassword(false);
        selected.setUseSshPubKey(false);
        selected.setSshPassPhrase("");
        selected.setSshPassword("");
        selected.setRdpResType(0);
        selected.setRdpWidth(0);
        selected.setRdpHeight(0);
        selected.setPassword(pwd);
        selected.setKeepPassword(true);
        selected.setUseDpadAsArrows(true);
        selected.setRotateDpad(false);
        selected.setUseLocalCursor(false);
        // selected.setEnableSound(true);
        return selected;
    }

    /**
     * 关闭虚拟机系统
     *
     * @author ch
     *
     */
    public class CloseVM extends AsyncTask<String, Void, Void> {

        String getjsonstr = null;
        String message = null;
        String conDyncpoolid;
        String conVmuid;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(String... param) {

            HttpUtilsApache httpGetorPostUtil = new HttpUtilsApache();
            String vmuid = param[0];
            String dyncpoolid = param[1];
            conDyncpoolid = dyncpoolid;
            conVmuid = vmuid;
            String ip = "172.16.0.2:80";

            Map<String, Object> params = new HashMap<String, Object>();

            params.put("username", Base64.encode(PersonalUserInfoConstant.username.getBytes()));
            params.put("password", Base64.encode(PersonalUserInfoConstant.password.getBytes()));
            params.put("callback", "?");
            params.put("act", Base64.encode("stopVM".getBytes()));
            // dyncpoolid动态池为空 表示是静态虚拟机 ； 否则是动态虚拟机
            if ("".equals(dyncpoolid) || dyncpoolid == null) { //静态
                params.put("vmuid", Base64.encode(vmuid.getBytes()));
            } else {//动态
            //    Log.v("CloudComputerActivity","dyncpoolid = "+dyncpoolid);
            //    Log.v("CloudComputerActivity","PersonalUserInfoConstant.userid = "+PersonalUserInfoConstant.userid);
                params.put("dyncpoolid", Base64.encode(dyncpoolid.getBytes()));
                params.put("userid", Base64.encode(PersonalUserInfoConstant.userid.getBytes()));
            }

            String url = "http://" + ip + "/dashboard/site/act";

            String strjson = "";

            strjson = httpGetorPostUtil.usHttpGet(url, params);

            if (strjson != null && !"".equals(strjson)) {
                int rtjson = strjson.indexOf("?(");
                if (rtjson == 0) {
                    getjsonstr = strjson.substring(2, strjson.length() - 1);
                } else {

                    if ("400".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_404;
                    } else if ("500".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_500;
                    } else if ("900".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_900;
                    } else if ("901".equals(rtjson)) {
                        message = "您当前网络较不稳定，请重试。";// HttpGetorPostUtil.HTTP_901;
                    } else if ("902".equals(rtjson)) {
                        message = "您当前网络较不稳定，请重试。";// HttpGetorPostUtil.HTTP_902;
                    } else if ("903".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_903;
                    }

                }
            }

            return null;
        }

        protected void onPostExecute(Void result) {
            if (message != null && !"".equals(message)) {
                Toast.makeText(CloudComputerActivity.this, message, Toast.LENGTH_LONG)
                        .show();
            } else {
                if (!"".equals(getjsonstr) && getjsonstr != null) {

                    try {
                        JSONObject dataJson = new JSONObject(getjsonstr);
                        String successflag = dataJson.getString("successflag")
                                .toString();
                        if ("1".equals(successflag)) {
                            // 移除原先登录进入虚拟机的信息
                            if ("".equals(conDyncpoolid)
                                    || conDyncpoolid == null) {
                                PersonalUserInfoConstant.conMap.remove(conVmuid);
                            } else {
                                PersonalUserInfoConstant.conMap.remove(PersonalUserInfoConstant.username
                                        + conDyncpoolid);
                            }

                            Toast.makeText(CloudComputerActivity.this, "成功关闭系统",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudComputerActivity.this, "关闭系统失败",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        Toast.makeText(CloudComputerActivity.this, "关闭系统出错，请联系管理员...",
                                Toast.LENGTH_LONG).show();
                    }
                }
            }

        }
    }

    /**
     * 重启虚拟机系统
     *
     * @author ch
     *
     */
    public class RebootVM extends AsyncTask<String, Void, Void> {

        String getjsonstr = null;
        String message = null;
        String conVmuid;
        String conDyncpoolid;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(String... param) {

            HttpUtilsApache httpGetorPostUtil = new HttpUtilsApache();
            String vmuid = param[0];
            String dyncpoolid = param[1];
            String ip = "172.16.0.2:80";

            conVmuid = vmuid;
            conDyncpoolid = dyncpoolid;

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("username", Base64.encode(PersonalUserInfoConstant.username.getBytes()));
            params.put("password", Base64.encode(PersonalUserInfoConstant.password.getBytes()));
            params.put("callback", "?");
            // dyncpoolid动态池为空 表示是静态虚拟机 ； 否则是动态虚拟机
            if ("".equals(dyncpoolid) || dyncpoolid == null) {
                params.put("vmuid", Base64.encode(vmuid.getBytes()));
            } else {
                params.put("dyncpoolid", Base64.encode(dyncpoolid.getBytes()));
                params.put("userid", Base64.encode(PersonalUserInfoConstant.userid.getBytes()));
            }
            // params.put("vmuid", Base64.encode(vmuid.getBytes()));
            params.put("act", Base64.encode("restartVM".getBytes()));

            String url = "http://" + ip + "/dashboard/site/act";
            String strjson = "";

            strjson = httpGetorPostUtil.usHttpGet(url, params);

            if (strjson != null && !"".equals(strjson)) {
                int rtjson = strjson.indexOf("?(");
                if (rtjson == 0) {
                    getjsonstr = strjson.substring(2, strjson.length() - 1);
                } else {
                    //message = strjson;
                    if ("400".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_404;
                    } else if ("500".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_500;
                    } else if ("900".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_900;
                    } else if ("901".equals(rtjson)) {
                        message = "您当前网络较不稳定，请重试。";// HttpGetorPostUtil.HTTP_901;
                    } else if ("902".equals(rtjson)) {
                        message = "您当前网络较不稳定，请重试。";// HttpGetorPostUtil.HTTP_902;
                    } else if ("903".equals(rtjson)) {
                        message = HttpUtilsApache.HTTP_903;
                    }
                }
            }

            return null;
        }

        protected void onPostExecute(Void result) {

            if (message != null && !"".equals(message)) {
                Toast.makeText(CloudComputerActivity.this, message, Toast.LENGTH_LONG)
                        .show();
            } else {
                if (!"".equals(getjsonstr) && getjsonstr != null) {

                    try {
                        JSONObject dataJson = new JSONObject(getjsonstr);
                        String successflag = dataJson.getString("successflag")
                                .toString();
                        if ("1".equals(successflag)) {
                            // 移除原先登录进入虚拟机的信息
                            if ("".equals(conDyncpoolid)
                                    || conDyncpoolid == null) {
                                PersonalUserInfoConstant.conMap.remove(conVmuid);
                            } else {
                                PersonalUserInfoConstant.conMap.remove(PersonalUserInfoConstant.username
                                        + conDyncpoolid);
                            }

                            Toast.makeText(CloudComputerActivity.this, "成功重启系统",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudComputerActivity.this, "重启系统失败",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        Toast.makeText(CloudComputerActivity.this, "重启系统出错，请联系管理员...",
                                Toast.LENGTH_LONG).show();
                    }
                }
            }

        }
    }
}
